import { addResource, updateResource } from '@/services/system/SystemController';
import {
  ModalForm,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { message } from 'antd';


const UserForm: React.FC<{
  data: System.ResourceInfo | null | 0;
  onClose: () => void;
  onFinish: () => void;
}> = ({ data, onClose, onFinish }) => {
  let is_new = data !== null && data === 0;
  let id = data !== null && data !== 0 ? data.id : 0;
  const { loading, run: postResource } = useRequest((data) => { return is_new ? addResource(data) : updateResource(id, data) }, {
    manual: true,
    throwOnError: true,
    onSuccess() { message.success('操作成功'); onFinish(); }
  })
  return (
    <ModalForm<System.ResourceInfo>
      title={is_new ? '新建' : '编辑'}
      open={data !== null}
      width={500}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: onClose,
      }}
      loading={loading}
      submitTimeout={2000}
      onFinish={postResource}
    >
      <ProFormText name="path" label="资源路径" placeholder="请输入资源路径" initialValue={(data !== 0 && data?.path) || ''} rules={[{ required: true, min: 1, max: 255 }]} />
      <ProFormTextArea name="description" label="描述" placeholder="请输入描述" initialValue={(data !== 0 && data?.description) || ''} />
      <ProFormSwitch name="status" label="状态" required initialValue={is_new ? true : data !== 0 && data?.status} />
    </ModalForm>
  );
};

export default UserForm;
